package com.example.My.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.My.mapper.UserMapper;
import com.example.My.pojo.LoginUser;
import com.example.My.pojo.User;
import com.example.My.service.UserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Author: 谢宇
 * CreatTime 2023/11/5 14:29
 * Version 1.0.0
 *
 *
 * 存放验证信息的方法
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService, UserService {
    @Resource
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> userLambdaQueryWrapper=new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(userLambdaQueryWrapper);
        if(user == null){
            throw new RuntimeException("没有该用户");
        }
        //返回一个UserDetails的对象使其封装了用户信息供SpringSecurity调用
        return new LoginUser(user);
    }

    @Override
    public UserDetails getByEmail(String principal) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper=new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getEmail,principal);
        User user = userMapper.selectOne(userLambdaQueryWrapper);
        if(user==null){
            throw new RuntimeException("该邮箱未注册");
        }
//        System.out.println("用户名"+user.getUserName());
        return new LoginUser(user);
    }
}
